<!--
 * @Descripttion:人员
 * @version:
 * @Author: ada.wu
 * @Date:2024-03-11 11:26:44
 * @LastEditors: ada.wu
 * @LastEditTime: 2024-04-08 15:00:21
-->
<template>
  <div class="bg-white hub">
    <div class="t-c p-tb-sm m-b-sm">
      <van-button round color="#ffd000" class="text-base m-t-sm t-m-x">请对{{evaluatedName}}进行评估</van-button>
    </div>
    <ExamList :examList="displayedExamList" :examDto="examDto" :currentPage="currentPage" :pageSize="pageSize"></ExamList>
    <div class="safe-height p-b-lg"></div>
    <div class="fixed_bottom p-b-lg" v-show="examList.length">
      <div class="flex publish bg-white p-t">
        <div class="basis-df t-c">
          <van-button round color="#ffd000" class="back" plain @click="goToPreviousPage">返回</van-button>
        </div>
        <div class="basis-df t-c">
          <van-button round color="#ffd000" @click="goToNextPage">
            {{currentPage==totalPage?'提交':"下一页"}}
            <template v-if="disNext">({{countdown}}s)</template>
          </van-button>
        </div>
      </div>
    </div>
    <!-- <van-cell v-for="(item,index) in displayedExamList" :key="index">
      <template #title>
        {{index+1}}***** {{item.examSubjectAns}}
      </template>
    </van-cell>
    <van-cell v-for="(item,index) in examList" :key="index">
      <template #title>
        {{index+1}}======== {{item.examSubjectAns}}
      </template>
    </van-cell> -->

    <van-empty v-if="examList.length==0&&!listLoading" description="暂无查询结果…" :image="getAssets('empty.svg')" />
    <van-dialog v-model:show="disShow" confirmButtonText='返回'>
      <div class="t-c">
        <img src="/@/assets/exam/warning.svg" class="m-t-lg" />
        <div class="text-black t-lx p-b-xs p-t t-c">您的答题过快请您认真答题</div>
        <div class="text-gray  p-b-sm  t-c">打分过快：每页{{examDto.pageQuestion}}个题，必须{{examDto.pageMinTime}}秒</div>
      </div>
    </van-dialog>

    <van-dialog v-model:show="equalShow" confirmButtonText='返回'>
      <div class="t-c">
        <img src="/@/assets/exam/warning.svg" class="m-t-lg" />
        <div class="text-black t-lx p-b-xs p-t">您的答题不符合要求，请返回修改后提交</div>
        <div class="text-gray  p-b-sm t-c" v-if="necessaryList.length">
          必答题未完成，题目：{{necessaryList.join(',')}}
        </div>
        <div class="text-gray  p-b-sm   t-c" v-if="npsList.length">
          分数雷同，全部为{{npsList[0]?npsList[0]:'0'}}分
        </div>
      </div>
    </van-dialog>

    <van-dialog v-model:show="confirmShow" confirmButtonText='确认提交' cancelButtonText="返回" :showCancelButton="true" @confirm="handelConfirm">
      <div class="t-c">
        <img src="/@/assets/exam/warning.svg" class="m-t-lg" />
        <div class="text-black t-lx p-tb">确认提交无法修改，是否确认</div>
      </div>
    </van-dialog>

    <van-dialog v-model:show="successShow" confirmButtonText='返回列表' :showCancelButton="false" @confirm="successConfirm">
      <div class="t-c">
        <img src="/@/assets/exam/success.svg" class="m-t-lg" />
        <div class="text-black t-lx p-tb">你的回答已被记录，提交成功</div>
      </div>
    </van-dialog>
  </div>
</template>
<script lang="ts">
import { PullRefresh, Divider } from "vant";
//util
import { onMounted, reactive, toRefs, ref, nextTick, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { PageEnum } from "/@/enums/pageEnum";
import { getNewObj } from "/@/util";
import { formatToDate } from "/@/util/dateUtil";
import moment from "moment";
import ExamList from "./components/examList.vue";
import ExamConfig from "/@/hooks/examConfig";

import { useStore } from "/@/store";
//api
import { answerExam, examAnswerDetail } from "/@/api/ExamApi";
export default {
  name: "reservation",
  components: {
    ExamList,
    [Divider.name]: Divider,
    [PullRefresh.name]: PullRefresh,
  },
  setup() {
    const store = useStore();

    const router = useRouter();
    const route = useRoute();
    let {
      status = "",
      evaluateId = "",
      examId = "",
      activityId = "",
      valuatorUserId = "",
      evaluatedName = "", //被评价者名称
      evaluatedUserId = "", //被评价者id
      pageQuestion = 3,
      pageMinTime = 10,
    } = route.query;
    console.error("status====", status);
    // 声明响应式状态变量
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(1); // 每页显示数量
    const totalItems = ref(0); // 总数据条目数
    const totalPage = ref(1); // 总页码

    const countdown = ref(0);
    let timerId;

    const state = reactive({
      isQuery: false,
      evaluatedName,
      disNext: false,
      disShow: false,
      confirmShow: false,
      successShow: false,
      equalShow: false,

      queryParam: {
        examId: examId,
      },
      necessaryList: <any>[],
      npsList: <any>[],
      examList: <any>[],
      //列表接口带过来
      examDto: <any>{
        pageQuestion,
        pageMinTime,
      },
      listLoading: false,
    });
    onMounted(async () => {
      getExamDetail();
      if (status != "2" && status != "3") {
        handelAnswerExam("1");
      }
    });

    /**
     * 获取详情
     */
    const getExamDetail = async () => {
      let res = await store.dispatch("exam/getExamDetail", {
        ...state.queryParam,
      });
      if (res) {
        state.examList = res.list || [];
        if (state.examList && state.examList.length) {
          state.examList.forEach((item: any) => {
            item.examSubjectValue = item.examSubjectValue
              ? JSON.parse(item.examSubjectValue)
              : [];
            item.examSubjectAns = "";
            //组装选项
            item.examSubjectValue.map((item: any) => {
              item._checked = false;
            });
          });
        }
        //暂存数据 反显
        if (status == "2") {
          let answerRes = await store.dispatch("exam/getExamAnswerDetail", {
            examId,
            evaluateId,
          });
          if (answerRes && answerRes.list) {
            answerRes.list.forEach((item: any) => {
              console.log(item.subjectId, item.ansValue);

              state.examList.find((sub: any) => {
                if (sub.id == item.subjectId) {
                  sub.examSubjectAns = item.ansValue;
                  console.log("sub==", sub);
                  if (sub.examSubjectValue) {
                    sub.examSubjectValue.find((ans: any) => {
                      if (ans.optionValue == item.ansValue) {
                        ans._checked = true;
                      }
                    });
                  }
                }
              });
            });
          }
          console.error("暂存===", answerRes);
        }

        totalItems.value = state.examList.length;
        // state.examDto = res.content;
        pageSize.value = state.examDto.pageQuestion
          ? parseInt(state.examDto.pageQuestion)
          : state.examList.length;
        totalPage.value = Math.ceil(totalItems.value / pageSize.value);
        if (state.examDto.pageMinTime)
          //倒计时
          countdown.value = state.examDto.pageMinTime
            ? parseInt(state.examDto.pageMinTime)
            : 0;
        if (countdown.value > 0) {
          handelStart();
        }
      } else {
        state.examList = [];
      }
    };
    function handelStart() {
      if (countdown.value > 0) {
        state.disNext = true;
        startCountdown();
      }
    }

    // 跳转到下一页
    function goToNextPage() {
      // getCheck();

      if (state.disNext) {
        state.disShow = true;
      } else {
        if (currentPage.value < totalPage.value) {
          currentPage.value++;
          handelStart();
        } else {
          getCheck();
          if (!getCheck()) {
            state.confirmShow = true;
          }
          console.log("最后一页了===");
        }
      }
    }

    // 跳转到上一页
    // 返回可以保存作答进度
    function goToPreviousPage() {
      if (currentPage.value > 1) {
        currentPage.value--;
      } else {
        handelAnswerExam("2");
        setTimeout(() => {
          router.back();
        }, 1000);
      }
    }

    // 跳转到上一页
    function getCheck() {
      let flag = false;
      state.npsList = [];
      state.necessaryList = [];
      let npsList = [] as any;
      state.examList.forEach((subject: any, index: any) => {
        if (subject.examSubjectType == ExamConfig().EXAM_SUBJECT_TYPE.NPS) {
          npsList.push(subject.examSubjectAns);
        }

        if (subject.isMust == "1") {
          //必填没填
          if (!subject.examSubjectAns) {
            state.necessaryList.push(index + 1);
          }
        }
      });

      console.log("npsList===", npsList);
      if (npsList.length > 1) {
        // 判断数组元素是否全都一样
        let areEqual = npsList.every((element: any) => element === npsList[0]);
        if (areEqual || state.necessaryList.length) {
          state.equalShow = true;
          flag = true;
          if (areEqual) {
            state.npsList = npsList;
          }
        }
        // console.log("areEqual=====", areEqual); // 输出: true 如果所有元素都相同，false 否则
      }

      // console.log(state.examList);
      return flag;
    }

    // 计算开始和结束索引
    const startIndex = computed(() => (currentPage.value - 1) * pageSize.value);
    const endIndex = computed(() =>
      Math.min(currentPage.value * pageSize.value, totalItems.value)
    );
    // 分页后的显示数据
    const displayedExamList = computed(() =>
      state.examList.slice(startIndex.value, endIndex.value)
    );

    // 开始倒计时函数
    function startCountdown() {
      timerId = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timerId);
          // 倒计时结束后的处理
          countdown.value = 0;
          // 可以在这里触发事件或者执行其他操作
          resetCountdown();
        }
      }, 1000); // 每隔1秒更新一次
    }

    // 重置倒计时
    function resetCountdown() {
      countdown.value = parseInt(state.examDto.pageMinTime);
      state.disNext = false;
    }
    function successConfirm() {
      router.push({
        path: PageEnum.EMPLOYEE,
        query: {
          activityId,
          valuatorUserId, //评价者
        },
      });
    }

    //获取答案
    const getAnswers = () => {
      let answers = <any>[];
      state.examList.map((item: any) => {
        //试题
        answers.push({
          subjectId: item.id, //题目ID
          ansValue: item.examSubjectAns, //答案
        });
      });
      return answers;
    };
    //试卷回答
    const handelAnswerExam = (_status = "") => {
      return new Promise(function (resolve, reject) {
        if (_status) {
          let model = {
            examId,
            activityId,
            valuatorUserId,
            evaluatedUserId,
            status: _status, //状态：1-已阅读，2-进行中，3-已完成
            answers: _status != "1" ? getAnswers() : [],
          };
          answerExam({ ...model })
            .then((res) => {
              resolve(true);
            })
            .catch(() => {
              resolve(false);
            });
        }
      });
    };
    async function handelConfirm() {
      let res = await handelAnswerExam("3");
      if (res) state.successShow = true;
    }
    return {
      ...toRefs(state),
      pageSize,
      totalPage,
      countdown,
      currentPage,
      goToPreviousPage,
      goToNextPage,
      displayedExamList,
      successConfirm,
      handelConfirm,
      handelAnswerExam,
    };
  },
};
</script>

<style lang="scss" scoped>
::v-deep(.van-cell) {
  align-items: center;
}
.publish {
  .back {
    background: #fffdf3 !important;
  }
  .van-button--round {
    font-weight: 500 !important;
    font-size: 16px !important;
    color: #1a1446 !important;
    width: 80%;
  }
}
</style>
